
local assert     = assert
local require    = require
local bit        = bit
local coroutine  = coroutine
local debug      = debug
local io         = io
local pairs      = pairs
local ipairs     = ipairs
local math       = math
local os         = os
local print      = print
local pcall      = pcall
local xpcall     = xpcall
local rawget     = rawget
local rawset     = rawset
local select     = select
local string     = string
local table      = table
local tonumber   = tonumber
local tostring	 = tostring
local error      = error
local type       = type
local unpack     = unpack
local setmetatable = setmetatable
local getmetatable = getmetatable
local ngx = ngx

local string_char  = string.char
local string_sub   = string.sub
local string_byte  = string.byte
local string_gsub  = string.gsub
local string_find  = string.find
local string_upper = string.upper

local math_fmod   = math.fmod
local math_floor  = math.floor
local math_pow    = math.pow
local math_abs    = math.abs

local table_insert = table.insert

local os_date = os.date;
local table_concat = table.concat;


local uu         = require("modules.commhm.utils");
local log        = require("modules.commhm.log");
local ns_time    = require("modules.commhm.time");
local ns_network = require("modules.commhm.network");
local ns_utf8    = require("modules.commhm.utf8");

local ns_auth_comm_checker = require("modules.commhm.auth_comm_checker")

local CHtmlTable = require( "modules.html_page.CHtmlTable" )


local table_tostring = table.tostring
local table_loadstring = table.loadstring



local FOO = {
	_VERSION = '0.12.1',

	show_txt = {},
	now_ = 0,
};



FOO.header = [[<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>@{TITLE}</title>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/angular.min.js"></script>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/cookie.min.js"></script>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/md5.js"></script>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/jquery-3.1.1.min.js"></script>
<script src="https://indevelop.mini1.cn:8088/oa/js_lib/miniajax.js"></script>
</head>
<body>]];


FOO.tail = [[
</body>
</html>
]];


FOO.show = function( data_, server_ip_list_ )

    FOO.now = uu.now()

	if  not data_.ip then
		data_.ip = 'no_ip'
	end

	local header_ = string.gsub( FOO.header, "@{TITLE}", "keeper_detail_" .. data_.ip )
	ngx.say( header_ )

	ngx.say( "<H2> openresty(OR)单节点管理 &nbsp&nbsp&nbsp&nbsp 请先更新git库-->" )

    local token_ = ns_auth_comm_checker.gen_comm_inner_token( 13011401, FOO.now, "sendKeeperMsg" )
	ngx.say( '<button style="background-color:#ff0033;width:150px;height:30px"'
		.. ' onclick=" press_pull_git(\'' .. token_ .. '\'); "'
		.. ' > ---- 更新 git ---- </button><br>【git库】-->【管理服】-->【目标服务器 ' .. data_.ip .. '】 </H2>'  )

	if  server_ip_list_ then
		ngx.say( '<H3><font color="red">【批量操作】</font>下面服务器会同时生效：</H3>' )
	end

	ngx.say( '<script type="text/javascript">' );

	ngx.say( 'var g_now=' .. FOO.now  .. ';\n' );
	ngx.say( 'var g_ip="' .. data_.ip .. '";\n' );

	if  server_ip_list_ then
		ngx.say( 'var g_server_ip_list_str_="' .. table_concat( server_ip_list_, ',' ) .. '";\n' );
	else
		ngx.say( 'var g_server_ip_list_str_="";\n' );
	end

	ngx.say( '</script>' );

	local fret_string_list_ = {}

	--data= {
		--nginx_list = { },
		--modules = { [1]=tools, [2]=modules/commhm, [3]=modules/client_config, },
		--msg=ok, ret=0, env=1, keeper_ver=20200826_02, hostname=dev-gameserver ,
	--}

	if type(data_) == 'table' then
		if  type( data_ ) == 'table' then
			local ip_ = data_.ip

			local tmp_keeper_info_ = {
				keeper_info_str  = "",
				or_list_info_str = "",
				env = data_.env or 99,
			}

			-------------------head
			local t_group_ = {
				keys = {
					"keeper_node",
					--"ip",
					--"hostname",
					--"env",
					--"ver",
					--"or_list",
				},

				style = {
					'width="150" ',   --valign="top"
				},

				data_style = {
					'valign="top"',
					'valign="top"',
					'valign="top"',
					'valign="top"',
					'valign="top"',
					'valign="top"',
				}
			}

			local keeper_node_str_ = (ip_ or "") .. '<br>'
				.. "env=" .. (data_.env or "") .. '<br>'
				.. "ver=" .. (data_.keeper_ver or "") .. '<br>'
				.. (data_.hostname or "") .. '<br>'

			if  server_ip_list_ then

				local str_ip_list_ = ""
				for i=1, #server_ip_list_ do
					if  #server_ip_list_[i] >= 7 then
						str_ip_list_ = str_ip_list_ .. i .. ' ' .. server_ip_list_[i] .. '<br>'
					end
				end

				keeper_node_str_ = keeper_node_str_	.. '<br><font color="red">批量操作列表:<br>'
						-- .. table_concat( server_ip_list_, '<br>' ) .. '</font>'
						.. str_ip_list_ .. '</font>'
			end

			keeper_node_str_ = keeper_node_str_  .. '<br>' .. FOO.create_common_checked_button()

			local tmp_group_ = {
				keeper_node = keeper_node_str_,
				--ip   = ip_,
				--env  = data_.env,
				--ver  = data_.keeper_ver,
				--hostname = data_.hostname
			}

			if  data_.modules then
				t_group_.keys[ #t_group_.keys + 1 ] = "modules"
				tmp_group_.modules =  FOO.create_modules_button(data_.modules, data_.modules_limit )
			end

			if  data_.nginx_list then
				t_group_.keys[ #t_group_.keys + 1 ] = "nginx_list"
				tmp_group_.nginx_list = FOO.create_nginx_list_button(data_.nginx_list)
			end

			t_group_[ #t_group_ + 1 ] = tmp_group_
			local ht_group_  = CHtmlTable:new( t_group_ )
			tmp_keeper_info_.keeper_info_str = ht_group_:get_print_string()

			fret_string_list_[ #fret_string_list_ + 1 ] = tmp_keeper_info_
		end
	end


	---需要进行排序
	local  sort_ = function( a, b )
		if  type( a ) == 'table' and type( b ) == 'table' then
			if  a.env and b.env and a.env < b.env then
				return true
			end
		end
		return false
	end

	table.sort( fret_string_list_, sort_ )

	ngx.say( '<table border=3 cellpadding=10>' )
	for i=1, #fret_string_list_ do
		ngx.say( '<tr><td>' )
		ngx.say( fret_string_list_[i].keeper_info_str )
		ngx.say( fret_string_list_[i].or_list_info_str )
		ngx.say( '</td></tr>' )
	end
	ngx.say( '</table>' )

	ngx.say( '<br><hr>' )
	ngx.say( FOO.ret_string )
	ngx.say( FOO.js_func )    	---增加js函数
	ngx.say( FOO.tail )

end




----------------------------------------------------------

FOO.font_modules_name = {
	["modules/commhm"] = 1,
	["modules/client_config"] = 1,
	["modules/html_page"]     = 1,
	["modules/center_server"] = 1,
	["modules/keeper_server"] = 1,
}


function FOO.get_module_font_color( name_ )
	if  FOO.font_modules_name[name_] then
		return '<font color="blue">' .. name_ .. '</font>'
	end
	return name_
end


--- 增加 dc ma_gate 等常用checked按钮
function FOO.create_common_checked_button()
	local str_ = '<button onclick=" press_select_checked(\'ma_gate\'); ">ma_gate</button>'
	str_ = str_ .. ' <button onclick=" press_select_checked(\'dc\'); "> dc </button>'
	str_ = str_ .. '<br><button onclick=" press_select_checked(\'map_profile\'); ">map_profile</button>'
	return str_
end


---按照更新的模块，生成按钮
function FOO.create_modules_button( modules_, modules_limit_ )

	local token_ = ns_auth_comm_checker.gen_comm_inner_token( 13011401, FOO.now, "sendKeeperMsg" )
	local str_ = '\n<table><tr><td><button style="background-color:#00ffff"'
		.. ' onclick=" press_rsync_modules(\'' .. token_ .. '\', 0); "'
		.. ' > 同 步 代 码 </button></td></tr>\n<tr><td>'

	local modules_filter_ = {}

	--log.debug( "===================1" )
	--uu.var_dump( modules_ )
	--log.debug( "===================2" )
	--uu.var_dump( modules_limit_ )

	for i=1, #modules_ do
		if  modules_limit_[ modules_[i] ] then
			modules_filter_[ #modules_filter_ + 1 ] = modules_[i]
		end
	end

	--log.debug( "===================3" )
	--uu.var_dump( modules_filter_ )

	local br_ = 10
	if  #modules_filter_ > 10 then
		br_ = math.ceil(#modules_filter_ / 2)
	end

	str_ = str_ .. '<font color="blue">蓝色:建议更新的公共模块</font><br>\n'

	local ii = 0
	for i=1, #modules_filter_ do
		local font_str_ = FOO.get_module_font_color( modules_filter_[i] )
		str_ = 	str_ .. '<input style="zoom:125%;" type="checkbox" name="cb_modules" class="cb"'
				.. ' onclick=" press_checkbox(this); "'
				.. ' value="' .. modules_filter_[i] .. '" />' .. font_str_ .. '<br>\n'
		ii = ii + 1
		if  ii % br_ == 0 then
			--str_ = str_ .. '</td><td>'
		end
	end

	str_ = str_ .. '</td></tr><tr><td><button style="background-color:#00ff88"'
		.. ' onclick=" press_rsync_modules(\'' .. token_ .. '\', 1); "'
		.. ' > 检查代码差异 </button></td></tr></table>'

	return str_
end


---按照nginx_list生成nginx列表
function FOO.create_nginx_list_button( nginx_list_ )

	local token_ = ns_auth_comm_checker.gen_comm_inner_token( 13011401, FOO.now, "sendKeeperMsg" )
	local str_ = '\n<table><tr><td><button style="background-color:#00ffff"'
		.. ' onclick=" press_reload_nginx_list(\'' .. token_ .. '\'); "'
		.. ' > reload 服 务 </button></td></tr>\n<tr><td>'

	local br_ = 10
	if  #nginx_list_ >= 10 then
		br_ = math.ceil(#nginx_list_ / 2)
	end

	local ii = 0
	for i=1, #nginx_list_ do
		if  nginx_list_[i].name then
			str_ = 	str_ .. '<input style="zoom:125%;" type="checkbox" name="cb_nginx_list" class="cb"'
                    .. ' onclick=" press_checkbox(this); "'
                    .. ' value="' .. nginx_list_[i].name .. '"/>'	.. nginx_list_[i].name .. '<br>\n'
			ii = ii + 1
			if  ii % br_ == 0 then
				--str_ = str_ .. '</td><td>'
			end
		end
	end

	str_ = str_ .. '</td></tr><tr><td>'
			.. '<button style="background-color:#00ff88"'
			.. ' onclick=" press_check_nginx_list(\'' .. token_ .. '\'); "'
			.. ' > 检查nginx进程 </button><br>'
			..	'<button style="background-color:#00ff88"'
			.. ' onclick=" press_clean_error_log(\'' .. token_ .. '\'); "'
			.. ' > 清理error日志 </button><br>'
			..	'<button style="background-color:#00ff88"'
			.. ' onclick=" press_list_error_log(\'' .. token_ .. '\'); "'
			.. ' > list error日志 </button><br>'
			..'</td></tr></table>'

	return str_
end



FOO.create_input_str = function( id_, value_, width_ )
	return '<input type=text id="' .. id_ .. '" style="width:' .. (width_ or 30)
			.. 'px; height:20px; border:solid 1px; text-align:center;" value="' .. (value_ or "") .. '" />'
end


FOO.create_img_str = function( value_, width_ )
	return '<image width=' .. (width_ or 30) .. ' src="' .. (value_ or "") .. '" ></image>'
end




FOO.ret_string = [[
<table>
<textarea id="_ret_string" style="width:770px;height:880px;background-color:#dddddd;" readonly="readonly">
 ... </textarea>
</table>
]];

FOO.js_func = [[
<script type="text/javascript">

	//填格子
	function load_press_history(){
		var history_modules_ = getCookie('KeeperDetail_modules');
		var history_nginx_   = getCookie('KeeperDetail_nginx_list');

		if ( history_modules_ ){
			//alert( "history_modules=" + history_modules_ );
			var save_ = history_modules_.split( "," );
			var id_lists = document.getElementsByName('cb_modules');
			for(var i = 0; i < id_lists.length; i++){
				for(var ii = 0; ii < save_.length; ii++){
					if ( id_lists[i].value == save_[ii] ){
						//alert( "find "+save_[ii] );
						id_lists[i].checked = true;
						id_lists[i].style="zoom:175%;";
					}
				}
			}
		}

		if (history_nginx_){
			//alert( "history_nginx=" + history_nginx_ );
			var save_ = history_nginx_.split( "," );
			var id_lists = document.getElementsByName('cb_nginx_list');
			for(var i = 0; i < id_lists.length; i++){
				for(var ii = 0; ii < save_.length; ii++){
					if ( id_lists[i].value == save_[ii] ){
						//alert( "find "+save_[ii] );
						id_lists[i].checked = true;
						id_lists[i].style="zoom:175%;";
					}
				}
			}
		}

	}

	load_press_history();


    function press_checkbox(this_){
        if (this_.checked){
            this_.style="zoom:175%;";
        }else{
            this_.style="zoom:125%;";
        }
    }

	function press_select_checked( name_ ){
		var save_ = [ 'modules/commhm', 'modules/center_server', 'modules/keeper_server', 'modules/html_page' ];
		if      ( name_ == "ma_gate" ) {
			save_[4] = "modules/ma_gate";
		}else if( name_ == "dc" ) {
			save_[4] = "modules/data_cache";
			save_[5] = "modules/dc_gate";
		}else if( name_ == "map_profile" ) {
			save_[4] = "modules/client_config";
			save_[5] = "modules/map";
		}else{
			alert(name_);
			return;
		};

		var id_lists = document.getElementsByName('cb_modules');
		for(var i = 0; i < id_lists.length; i++){
			id_lists[i].checked = false;
			id_lists[i].style="zoom:125%;";
			for(var ii = 0; ii < save_.length; ii++){
				if ( id_lists[i].value == save_[ii] ){
					id_lists[i].checked = true;
					id_lists[i].style="zoom:175%;";
				}
			}
		}



	}

	function press_rsync_modules( token_, dry_ ){
		var id_lists = document.getElementsByName('cb_modules');
		var value_str = "";
		for(var i = 0; i < id_lists.length; i++){
			if(id_lists[i].checked){
				value_str = value_str + id_lists[i].value + ','
			}
		}
		setCookie( "KeeperDetail_modules", value_str, "d30" );
		if ( dry_ == 1 ) {
			send_msg( "rsync_code_dry", value_str, token_ );
		}else{
			send_msg( "rsync_code",     value_str, token_ );
		}
	}

	function press_reload_nginx_list( token_ ){
		var id_lists = document.getElementsByName('cb_nginx_list');
		var value_str = "";
		for(var i = 0; i < id_lists.length; i++){
			if(id_lists[i].checked){
				value_str = value_str + id_lists[i].value + ','
			}
		}
		setCookie( "KeeperDetail_nginx_list", value_str, "d30" );
		send_msg( "reload_nginx_by_config", value_str, token_ );
	}


	function press_check_nginx_list( token_ ){
		var id_lists = document.getElementsByName('cb_nginx_list');
		var value_str = "";
		for(var i = 0; i < id_lists.length; i++){
			if(id_lists[i].checked){
				value_str = value_str + id_lists[i].value + ','
			}
		}
		send_msg( "get_nginx_list", value_str, token_ );
	}

	function press_clean_error_log( token_ ){
		send_msg( "clean_error_log", "", token_ );
	}

	function press_list_error_log( token_ ){
		send_msg( "list_error_log", "", token_ );
	}

    function press_pull_git( token_ ){
        send_msg( "press_pull_git", "", token_ );
    }

	function send_msg( op_, value_, token_ ){

		var press_yes = false;
		if ( op_ == "get_nginx_list" || op_ == "rsync_code_dry" || op_ == "list_error_log" ) {
			press_yes = true;
		}else{
			press_yes = confirm( op_ + " " + g_ip + "\n" + value_ + "\n\n是否确定？" );
		}

		if (press_yes) {
			//get请求
			document.getElementById("_ret_string").innerHTML = " waiting ... ";

			var url_ = "";
			if ( op_.length > 2 ) {
				url_ = "/miniw/center?cmd=sendKeeperMsg&time="+g_now+"&op="+op_+"&ip="+g_ip
				        +"&uin=13011401&token="+token_;
				if  ( op_ == "rsync_code" ) {
					url_ = url_ + "&modules_list=" + value_;
				}else if ( op_ == "rsync_code_dry" ) {
					url_ = url_ + "&modules_list=" + value_;
				}else if ( op_ == "reload_nginx_by_config" ) {
					url_ = url_ + "&config_file_list=" + value_;
				}else if ( op_ == "get_nginx_list" ) {
					url_ = url_ + "&config_file_list=" + value_;
				}else if ( op_ == "clean_error_log" ) {
				}else if ( op_ == "list_error_log" ) {
				}else if ( op_ == 'press_pull_git' ) {
				}else{
                    alert( "unknown op=" + op_ );
				}
				//alert( "url=" + url_ );
			}
			else{
				alert( "unknown op=" + op_ );
				return;
			}

			if  ( g_server_ip_list_str_.length > 0 ) {
				url_ = url_ + "&server_ip_list=" + g_server_ip_list_str_;
			}

			var post_data_ = {};
			ajax({
				url: url_,
				type: "POST",
				data: post_data_,
				dataType: "json",
				success: function (response, xml) {
					document.getElementById("_ret_string").innerHTML = response;
					//alert( response );
					//location.reload();
				},
				fail: function (status) {
					alert( "服务器通讯失败，请联系海马 ......" );
				}
			});
		}
	}

</script>
]];



-----------------------------------------------------------
---清理输出
FOO.clean_txt = function()
	FOO.show_txt = {};
end

---增加输出内容
FOO.add_txt = function( txt_ )
	FOO.show_txt[ #FOO.show_txt + 1 ] = txt_
end


---获得所有输出
FOO.get_txt = function()
	return table_concat( FOO.show_txt )
end


return FOO;